05. 默认参数

默认参数值

现在我们来重新看看在前面的课程中(数据结构和循环 -> For循环)出现的 starbox 函数,不过这次我们作了一处修改。这个 box 函数可使用任何符号绘制方框,而不仅仅是 *

def box(width, height, symbol):
    """print a box made up of asterisks, or some other character.

    width: width of box in characters, must be at least 2
    height: height of box in lines, must be at least 2
    symbol: a single character string used to draw the box edges
    """
    print(symbol * width) # print top edge of box

    # print sides of box
    for _ in range(height-2):
        print(symbol + " " * (width-2) + symbol) 

    print(symbol * width) # print bottom edge of box

这个新增功能非常好,但是调用该函数时,你还必须多指定一个参数。如果你只想绘制一个方框,而不在乎使用什么符号,这个功能反倒有些累赘了。但幸好 Python 有一个功能,可使参数具有灵活性,也可以指定默认参数。

我们可以通过对函数的第一行做出以下更改,来指定 symbol 参数的默认值:

def box(width, height, symbol='*'):

现在我们可以传入两个参数或三个参数来调用函数。如果第三个参数被省略,那么则使用 * 作为默认值。

>>> box(7, 5)
*******
*     *
*     *
*     *
*******

>>> box(7, 5, '#')
#######
#     #
#     #
#     #
#######

练习:默认参数

在下面的练习中, print_list 函数以列表作为输入,并逐行打印列表内的元素,以数字编号或项目符号开头。该函数具有三个参数:

  • l :要打印的列表
  • numbered :设置为 True 时打印编号列表。
  • bullet_character :置于每个列表元素之前的项目符号。如果 numbers True ,则忽略。

这样的函数在调用时很麻烦,即使用户想要的是一个以数字编号开头的序列,也仍然需要指定一个 bullet_character 参数。

现在请你添加默认参数,使函数的使用更加简便。在默认情况下,该函数可以以项目符号开头打印列表中的元素,默认的项目符号应为 "-"。

更改后,该函数的输出如下所示:

>>> print_list(["cats", "in", "space"])
- cats
- in
- space
>>> print_list(["cats", "in", "space"], True)
1: cats
2: in
3: space

Start Quiz:

def print_list(l, numbered, bullet_character):
    """Prints a list on multiple lines, with numbers or bullets
    
    Arguments:
    l: The list to print
    numbered: set to True to print a numbered list
    bullet_character: The symbol placed before each list element. This is
                      ignored if numbered is True.
    """
    for index, element in enumerate(l):
        if numbered:
            print("{}: {}".format(index+1, element))
        else:
            print("{} {}".format(bullet_character, element))

练习:可变默认参数

默认参数是一个相当有用的功能,但在一种情况下例外。如果使用可变类型(如列表或字典)作为默认参数,在修改这个参数后可能会导致奇怪的结果。因此,你最好避免使用可变的默认参数。你可以在本地尝试以下代码以查看原因:

有一个函数可将项目添加到待办事项列表。用户可以提供自己的待办事项列表,或将项目添加到默认列表中:

def todo_list(new_task, base_list=['wake up']):
    base_list.append(new_task)
    return base_list

我们可以像这样调用该函数:

>>> todo_list("check the mail")
['wake up', 'check the mail']

之后,一名宇航员调用该函数为自己创建一个待办事项列表:

>>> todo_list("begin orbital transfer")

todo_list 返回什么结果?

SOLUTION: `['wake up', 'check the mail', 'begin orbital transfer']`